package com.pay.ioopos.activity;

import android.content.Intent;
import android.os.Bundle;

import com.pay.ioopos.DataFactory;
import com.pay.ioopos.DataStore;
import com.pay.ioopos.KeyInfo;
import com.pay.ioopos.PwdListener;
import com.pay.ioopos.R;
import com.pay.ioopos.ScanListener;
import com.pay.ioopos.fragment.DomainListFragment;
import com.pay.ioopos.fragment.DomainScanFragment;
import com.pay.ioopos.fragment.ComPwdValidFragment;
import com.pay.ioopos.fragment.TipVerticalFragment;

import static com.pay.ioopos.KeyInfo.KEY_CANCEL;
import static com.pay.ioopos.KeyInfo.KEY_ENTER;
import static com.pay.ioopos.fragment.TipFragment.TipType.SUCCESS;

public class DomainActivity extends AbstractActivity implements PwdListener, ScanListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_domain);
        ComPwdValidFragment fragment = new ComPwdValidFragment();
        fragment.setPwdListener(this);
        setMainFragment(fragment);

    }

    @Override
    public boolean onKeyDown(KeyInfo keyInfo) {
        if (keyInfo == KEY_ENTER || keyInfo == KEY_CANCEL) {
            Intent intent = new Intent(this, ConnectActivity.class);
            startActivity(intent);
            return true;
        } else if (mainFragment instanceof ComPwdValidFragment) {
            ComPwdValidFragment fragment = ((ComPwdValidFragment)mainFragment);
            fragment.onKeyDown(keyInfo);
            return true;
        } else if (mainFragment instanceof DomainListFragment) {
            int num;
            try {
                num = Integer.parseInt(keyInfo.getValue());
            } catch (NumberFormatException e) {
                return false;
            }

            int length = DomainListFragment.domains.length;
            if (num <= 0 || num > length) {
                return false;
            }

            if (num == length) {
                DomainScanFragment scanFragment = new DomainScanFragment();
                scanFragment.setListener(this);
                setMainFragment(scanFragment);
                return true;
            } else {
                setDomain(DomainListFragment.domains[num - 1]);
                return true;
            }

        }
        return false;
    }

    @Override
    public void onPwdValid(String pwd) {
        setMainFragment(new DomainListFragment());
    }

    @Override
    public boolean onScan(String content) {
        String[] params = content.split("\\|");
        DataStore store = DataFactory.getDataStore();
        if (params.length > 1) {
            store.setTransKey(params[1]);
        }
        setDomain(params[0]);
        return true;
    }

    private void setDomain(String domain) {
        DataFactory.getDataStore().setServerUrl(domain);
        setMainFragment(new TipVerticalFragment(SUCCESS, "域名设置成功"));
    }

}
